package com.wing.wcabinet.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.cabinet.model.entity.Cabinet;
import com.wing.cabinet.model.entity.EnterpricceId;
import com.wing.cabinet.model.request.CabinetForm;
import com.wing.cabinet.model.response.CabinetVO;
import com.wing.cabinet.service.CabinetService;
import com.wing.cabinet.service.EnterpricceIdService;
import com.wing.common.utils.HttpHelper;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author
 */
@Validated
@Api(value = "Admin-刀柜管理", tags = "#/wcabinet/wcabinet")
@RestController("wcabCabinetController")
@RequestMapping("wcabinet/admin/wcabinet")
@RequiredArgsConstructor
public class WcabCabinetController {

    private final CabinetService cabinetService;
    @Autowired
    private EnterpricceIdService enterpricceIdService;

    @Value("${platform.gatewayUrl}")
    private String url;

    @ApiOperation(value = "查询所有刀柜", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "sort", value = "排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "order", value = "排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "cabinetTypeId", value = "刀柜类型ID", defaultValue = "cabinetTypeId", example = "cabinetTypeId", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "cabinetBrandId", value = "刀柜品牌id", defaultValue = "cabinetBrandId", example = "cabinetBrandId", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "status", value = "状态", defaultValue = "status", example = "status", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "code", value = "刀柜编码", defaultValue = "code", example = "code", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<CabinetVO> list(
            @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer limit
            , @RequestParam(defaultValue = "create_time") String sort
            , @RequestParam(defaultValue = "asc") String order
            , @RequestParam(defaultValue = "") String cabinetTypeId
            , @RequestParam(defaultValue = "") String cabinetBrandId
            , @RequestParam(required = false) Integer status
            , @RequestParam(defaultValue = "") String code
            , Cabinet.CabinetNature cabinetNature
            ,Cabinet.CabinetType cabinetType
    ){

        Page<CabinetVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }
        if (StringUtils.isNotBlank(cabinetTypeId)) {
            params.put("cabinetTypeId", cabinetTypeId);
        }
        if (StringUtils.isNotBlank(cabinetBrandId)) {
            params.put("cabinetBrandId", cabinetBrandId);

        }
        if (Objects.nonNull(status)) {
            params.put("status", status);

        }
        if (StringUtils.isNotBlank(code)) {
            params.put("code", code);

        }
        if (cabinetNature!=null){
            params.put("cabinetNature",cabinetNature.getValue());
        }
        if (cabinetType!=null){
            params.put("cabinetType",cabinetType.getValue());
        }
        params.put("enterpriseCode", JwtUtils.getEnterpriseCode());
        //同步数据
        //synchronizeCabinet();
        //搜索
        params.put("cabinetType",Cabinet.CabinetType.gravity.getValue());
        Page<CabinetVO> list = cabinetService.pageList4app(pg, params);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "查询刀柜详情", notes = "搜索")
    @GetMapping("/queryDetail")
    public JsonResult<CabinetVO> queryDetail(@RequestParam("cabCode") String cabCode) {
        CabinetVO cabinetVO = cabinetService.myInventory(cabCode,null);
        return JsonResult.success(cabinetVO);
    }


    @ApiOperation(value = "添加刀柜", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(CabinetForm.Add.class) CabinetForm cabinetForm) {

        if (cabinetService.add(cabinetForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }


    @ApiOperation(value = "修改刀柜", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(CabinetForm.Update.class) CabinetForm cabinetForm) {
        Cabinet cabinet = cabinetService.getById(cabinetForm.getId());
        if (cabinet == null) {
            return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(Cabinet.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(cabinetForm, cabinet, copyOptions);
        if (cabinetService.updateById(cabinet)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }


    @ApiOperation(value = "删除刀柜", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cabinetId", value = "刀柜id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long cabinetId) {
        if (cabinetService.removeById(cabinetId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    /**
     * 同步刀柜
     *
     * @return {@link JsonResult}
     */
    @ApiOperation(value = "同步刀柜", notes = "同步")
    @PostMapping("/synchronizeCabinet")
    public JsonResult synchronizeCabinet() throws Exception {
        final String reqUri = url + "platformCab/cabinet/admin/cabinet/getSettledCompanyId?settledCompanyId=";
        EnterpricceId enterpricceId = enterpricceIdService.list().get(0);
        String tokenJson = HttpHelper.httpGet(reqUri + enterpricceId.getEnterpriseId());
        //String数据转JSONObject对象
        JSONObject jsonObject = JSON.parseObject(tokenJson);
        //获取data对应数据转JSONArray
        JSONArray array = jsonObject.getJSONArray("data");
        //JSONArray 转list对象数组
        List<Cabinet> list = JSONArray.parseArray(array.toJSONString(), Cabinet.class);
        if (list.size() > 0) {
            cabinetService.saveBatch(list);
        }
        return JsonResult.success(tokenJson);
    }

    /**
     * 查询柜子
     * @return
     */
    @ApiOperation(value = "查询柜子", notes = "查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cabinetNature", value = "状态:main(0,主柜);sale(1,售刀副柜);live(2,存刀副柜)", required = true, dataType = "string", paramType = "path")
    })
    @GetMapping("/getCabinetAll")
    public JsonResult<List<Cabinet>> getProductTypeVOAll(Cabinet.CabinetNature cabinetNature){
        QueryWrapper<Cabinet> wrapper = new QueryWrapper<>();
        if (cabinetNature!=null){
            wrapper.eq("cabinet_Nature",cabinetNature.getValue());
        }
        //wrapper.select("id","cab_code","");
        List<Cabinet> list = cabinetService.list(wrapper);
        return JsonResult.success(list);
    }

    @ApiOperation(value = "修改刀柜所属企业信息", notes = "修改")
    @PutMapping("/updateCompany")
    public JsonResult updateCompany(@Validated(CabinetForm.Update.class) CabinetForm cabinetForm) {
        //id查询主柜信息
        Cabinet cabinet = cabinetService.getById(cabinetForm.getId());
        if (cabinet == null) {
            return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(Cabinet.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(cabinetForm, cabinet, copyOptions);

        Map<String, Object> params = new HashMap<>();
        params.put("settledCompanyId",cabinetForm.getSettledCompanyId());
        params.put("workshopLocation",cabinetForm.getWorkshopLocation());
        params.put("id",cabinetForm.getId());
        params.put("cabCode",cabinet.getCabCode());
        params.put("settledCompanyName",cabinetForm.getSettledCompanyName());
        params.put("cabName",cabinetForm.getCabName());
        //修改主柜信息/副柜信息
        int result=cabinetService.updateCompany(params);
        if (result>0){
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }

    @ApiOperation(value = "查询所有主柜", notes = "查询")
    @GetMapping("/getCabinetByCabinetNature")
    public JsonResult getCabinetByCabinetNature() {
        return JsonResult.success(cabinetService.getCabinetByCabinetNature());
    }
}
